package com.lagou.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.lagou.entity.Position;
import com.lagou.repository.PositionRepository;
import com.lagou.service.PositionService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.BoostingQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

@Slf4j
@Service
public class PositionServiceImpl implements PositionService {

    @Autowired
    private PositionRepository positionRepository;

    @Autowired
    private RestHighLevelClient client;
    private static final String POSITION_INDEX = "position";

    @Override
    public List<Map<String, Object>> searchPos(String keyword) {
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        int pageSize = 5;

        // 搜索
        SearchRequest searchRequest = new SearchRequest(POSITION_INDEX);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchQueryBuilder positionNameQueryBuilder = QueryBuilders.matchQuery("positionname", keyword);
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.query(positionNameQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("IOException: ", e);
        }
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            list.add(hit.getSourceAsMap());
        }

        pageSize = 5 - list.size();

        if (pageSize <= 0) {
            return list;
        }

        // 不够5条数据查询福利最好的补全
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchQueryBuilder positionadvantageQueryBuilder = QueryBuilders.matchQuery("positionadvantage", "美女多 员工福利好");
        boolQueryBuilder.mustNot(positionNameQueryBuilder);
        boolQueryBuilder.must(positionadvantageQueryBuilder);

        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 执行搜索
        searchRequest.source(searchSourceBuilder);
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("IOException: ", e);
        }
        hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            list.add(hit.getSourceAsMap());
        }

        return list;
    }

    @Override
    public void importData() {
        BulkProcessor bulkProcessor = getBulkProcessor(client);

        List<Position> all = positionRepository.findAll();
        all.forEach(position -> {
            log.info("Position:{}", position);
            Map<String, Object> stringObjectMap = new HashMap<>();
            BeanUtil.beanToMap(position, stringObjectMap, CopyOptions.create().setFieldValueEditor(new BiFunction<String, Object, Object>() {
                @Override
                public Object apply(String s, Object o) {
                    if ("createtime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("generatetime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("borntime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("offlinetime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("advicetime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("verifytime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("adstarttime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("adendtime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("weightstarttime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("weightendtime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    } else if ("prolongOfflineTime".equals(s)) {
                        return ObjectUtil.isNull(o) ? "" : o.toString();
                    }
                    return o;
                }
            }));
            log.info("stringObjectMap:{}", stringObjectMap);
            bulkProcessor.add(new IndexRequest(POSITION_INDEX).source(stringObjectMap));
        });

        bulkProcessor.flush();
        try {
            bulkProcessor.awaitClose(150L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("InterruptedException:", e);
        }
    }

    private BulkProcessor getBulkProcessor(RestHighLevelClient client) {

        BulkProcessor bulkProcessor = null;
        try {

            BulkProcessor.Listener listener = new BulkProcessor.Listener() {
                @Override
                public void beforeBulk(long executionId, BulkRequest request) {
                    log.info("Try to insert data number : "
                            + request.numberOfActions());
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request,
                                      BulkResponse response) {
                    log.info("************** Success insert data number : "
                            + request.numberOfActions() + " , id: " + executionId);
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
                    log.error("Bulk is unsuccess : " + failure + ", executionId: " + executionId);
                }
            };

            BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer = (request, bulkListener) -> client
                    .bulkAsync(request, RequestOptions.DEFAULT, bulkListener);

            BulkProcessor.Builder builder = BulkProcessor.builder(bulkConsumer, listener);
            builder.setBulkActions(5000);
            builder.setBulkSize(new ByteSizeValue(100L, ByteSizeUnit.MB));
            builder.setConcurrentRequests(10);
            builder.setFlushInterval(TimeValue.timeValueSeconds(100L));
            builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), 3));
            // 注意点：让参数设置生效
            bulkProcessor = builder.build();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                bulkProcessor.awaitClose(100L, TimeUnit.SECONDS);
            } catch (Exception e1) {
                log.error(e1.getMessage());
            }
        }
        return bulkProcessor;
    }
}
